<template>
  <el-card shadow="never">
    <el-scrollbar  height="calc(100vh - 200px)">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px">
          <span style="font-size: 18px;margin-left: 7px">任务配置</span>
        <div style="display: flex; gap: 5px">
          <el-button type="primary" @click="clickSetEdit">保存</el-button>
          <el-button type="info" @click="clickSetting">导入预设配置</el-button>
        </div>
      </div>
      <el-form :model="configForm"  :rules="rulesConfig" ref="ConfigRef" label-width="95px" >
        <el-form-item label="任务类型：" prop="taskType">
          {{ taskTypeMap[configForm.taskType] || configForm.taskType}}
        </el-form-item>
        <el-form-item prop="name" label="配置名称：" >
          <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
        </el-form-item>
        <el-form-item v-if="configForm.taskType==='20'" label="时间配置：" prop="rule">
          <el-popover
            v-model:visible="cronVisible"
            placement="bottom-start"
            width="30">
            <template #reference>
              <el-input
                v-model="configForm.rule"
                clearable
                readonly
                placeholder="请选择定时任务时间配置"
                @click="cronFun"
              />
            </template>
            <timerTaskCron
              :runTimeStr="configForm.rule"
              @closeTime="closeRunTimeCron"
              @runTime="runTimeCron"
            >
              </timerTaskCron>
          </el-popover>
        </el-form-item>
        <el-form-item prop="logMode" label="日志模式：" >
          <el-select  v-model="selectedLogMode" placeholder="请选择日志模式" style="width: 100%">
            <el-option label="关闭" value=0></el-option>
            <el-option label="开启-全部日志" value=10></el-option>
            <el-option label="开启-仅成功日志" value=20></el-option>
            <el-option label="开启-仅失败日志" value=30></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="控制模式：" prop="control">
          <el-select v-model="selectControlMode" placeholder="请选择控制模式" style="width: 100%">
            <el-option label="集合模式" value=10></el-option>
            <el-option label="单独模式" value=20></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="压测模式：" prop="pressureMode">
          <el-select v-model="selectPressureMode" placeholder="请选择压测模式" style="width: 100%">
            <el-option label="并发模式" value='10'></el-option>
            <el-option label="阶梯模式" value='20'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长单位：" prop="pressureMode">
          <el-select v-model="configForm.timeUnit" placeholder="请选择时长单位" style="width: 100%">
            <el-option label="s" value="s"></el-option>
            <el-option label="m" value="m"></el-option>
            <el-option label="h" value="h"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="思考时间：" prop="thinkTime">
                  <el-select v-model="selectTimeType" placeholder="请选择时间类型" style="width: 100%;margin-bottom: 10px">
                    <el-option label="固定" value='10'></el-option>
                    <el-option label="随机" value='20'></el-option>
                  </el-select>
                  <span v-if="configForm.thinkTimeType === '20'">
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                    <span style="margin-right: 5px;margin-left: 5px">-</span>
                    <el-input-number
                      v-model="configForm.thinkTime[1]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                  <span v-else>
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                </el-form-item>
        <el-form-item style="margin-top: 15px;margin-bottom: 15px" label="运行机器：" prop="resource">
          <el-radio-group v-model="configForm.resource">
            <el-radio  label="10" @click="clickResource('10')">默认
              <el-tooltip content="使用机器管理中默认机器运行" :enterable="false" placement="top">
                <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
              </el-tooltip>
            </el-radio>
            <el-radio  label="20" @click="clickResource('20')">
              自定义
              <el-tooltip content="支持选择多机器分布式运行" :enterable="false" placement="top">
                <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-card v-if="configForm.pressureMode==='10'" style="background-color: #f5f7f9" class="card" shadow="always">
          <el-form label-width="120px" :model="FormConcurrency"  :rules="rulesConcurrencyMode" ref="CaseRef">
            <el-form-item label="并发用户数：" prop="concurrencyNumber">
              <el-input v-model="FormConcurrency.concurrencyNumber"></el-input>
            </el-form-item>
            <el-form-item label="并发数步长：" prop="concurrencyStep">
              <el-input v-model="FormConcurrency.concurrencyStep"></el-input>
            </el-form-item>
            <el-form-item label="持续时长：" prop="lastLong">
              <el-input v-model="FormConcurrency.lastLong"></el-input>
            </el-form-item>

          </el-form>
        </el-card>
        <el-card v-if="configForm.pressureMode==='20'" style="margin-left: 7px;margin-right: 4px;background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="125px" :model="FormLadder" :rules="rulesLadderMode" ref="CaseRef">
                    <div v-for="(ladder, index) in FormLadder.ladders" :key="index">
                      <div style="color: #606266; display: flex; align-items: center; justify-content: space-between;">
                        <span>阶梯{{ index + 1 }}</span>
                        <el-button
                          :disabled="index < 1"
                          size="mini"
                          type="text"
                          @click="removeLadder(index)"
                        >
                          删除
                        </el-button>
                      </div>
                      <el-form-item label="并发用户数：" :prop="'ladders.' + index + '.concurrencyNumber'">
                        <el-input v-model="ladder.concurrencyNumber"></el-input>
                      </el-form-item>
                      <el-form-item label="并发数步长：" :prop="'ladders.' + index + '.concurrencyStep'">
                        <el-input v-model="ladder.concurrencyStep"></el-input>
                      </el-form-item>
                      <el-form-item label="阶梯持续时长：" :prop="'ladders.' + index + '.lastLong'">
                        <el-input v-model="ladder.lastLong"></el-input>
                      </el-form-item>
                    </div>
                  </el-form>
                  <el-button  style="width: 100%;margin-top: 20px; background-color: #ecf5ff; color: #409eff;" @click="addLadder" >
                    add Data
                  </el-button>
                </el-card>
        <el-table
            v-if="configForm.resource==='20'"
            height="200"
            :data="serverData"
            style="width: 100%; margin-top:15px; margin-bottom: 35px"
            border="true"
            @selection-change="handleSelectionChange"
            ref="serverTable"
        >
        <el-table-column type="selection" width="40px" />
        <el-table-column align="center" prop="name" label="机器名称"  />
        <el-table-column align="center" prop="host_ip" label="IP" width="130px"/>
      </el-table>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!--导入预设配置弹窗-->
  <el-dialog title="导入预设配置" v-model="SettingDlg" destroy-on-close :before-close="handleClose" width="80%" top="10px">
    <makeSet :setButton="setButton" :taskType="configForm.taskType" @set-dlg="handleClose"  @set-data="handleSetData" ></makeSet>
  </el-dialog>
</template>

<script>
import {mapMutations, mapState} from "vuex";
import makeSet from './makeSet.vue'
import timerTaskCron from "@/components/common/timerTaskCron";
export default {
  components: {
    makeSet,
    timerTaskCron
  },
  data() {
    return {
      taskTypeMap: {'10': '普通任务', '20': '定时任务'},
      cronVisible: false,
      configForm: {
        name: '',
        rule: '',
        taskType: '',
        logMode: '0',
        pressureMode: '10',
        timeUnit: 's',
        control: '20',
        resource: '10',
        pressureConfig: {},
        serverArray: [],
        project: '',
        creator: '',
        thinkTimeType:'10',
        thinkTime:[0],
      },
      FormConcurrency:{
          lastLong:'',
          concurrencyNumber:'',
          concurrencyStep:''
        },
      FormLadder: {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      },
      rulesConfig: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        thinkTime: [{ required: true, message: '请输入思考时间', trigger: 'blur' }]

      },
      rulesConcurrencyMode: {
        lastLong: [{ required: true, message: '请输入持续时长', trigger: 'blur' }],
        concurrencyNumber: [{ required: true, message: '请输入并发数', trigger: 'blur' }],
        concurrencyStep: [{ required: true, message: '请输入步长', trigger: 'blur' }]
      },
      SettingDlg: false,
      setButton: true,
      serverData: [],
      defaultSelection: [],
      Selection:[],
      rulesLadderMode: {},
    }
  },
  computed: {
    ...mapState({
      ...mapState(['perfTask']),
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
      return window.sessionStorage.getItem('username');
    },
    selectedLogMode: {
      get() {
        return this.configForm.logMode.toString();
      },
      set(value) {
        this.configForm.logMode = Number(value);
      }
    },
    selectPressureMode: {
      get() {
        return this.configForm.pressureMode.toString();
      },
      set(value) {
        this.configForm.pressureMode = value;
      }
    },
    selectControlMode: {
      get() {
        return this.configForm.control.toString();
      },
      set(value) {
        this.configForm.control = Number(value);
      }
    },
    selectTimeType: {
      get() {
        return this.configForm.thinkTimeType.toString();
      },
      set(value) {
        this.configForm.thinkTimeType = value;
      }
     },

  },
  mounted() {
    this.configForm.taskType = this.perfTask.taskType;
    this.setRules();
  },
  watch: {
    'configForm.thinkTimeType'(newType) {
      if (newType === '20') {
        this.configForm.thinkTime = [this.configForm.thinkTime[0], this.configForm.thinkTime[1]];
      } else {
        this.configForm.thinkTime = [this.configForm.thinkTime[0]];
      }
    }
  },
  methods: {
    handleClose(done) {
      this.SettingDlg = done;
      this.SettingDlg = false
    },

    handleSetData(data) {
      this.configForm = data;
      const selectedIds = this.configForm.serverArray;
      this.Selection = this.serverData.filter(item => selectedIds.includes(item.id));
      if (this.configForm.pressureMode==='10') {
        this.FormConcurrency = data.pressureConfig
      }
      else if (this.configForm.pressureMode==='20') {
        this.FormLadder = data.pressureConfig
      }
      this.$nextTick(()=>{
             if (this.$refs.serverTable) {
                  this.Selection.forEach(row => {
                      this.$refs.serverTable.toggleRowSelection(row, true);
                  });
              } else {
                  console.error('serverTable is undefined');
              }
          })
    },

    async getPresetting() {
     const response =await this.$api.getPresetting(
         {
           project_id: this.pro.id,
           isSetting: true,
           task: this.perfTask.id
         })
     if (response.status ===200){
       if (response.data.result.length>0){
          this.handleSetData(response.data.result[0]);
       }
			}
    },

    clickResource(type) {
      if (type==='20') {
      setTimeout(() => {
        this.$nextTick(()=>{
             if (this.$refs.serverTable) {
                  this.Selection.forEach(row => {
                      this.$refs.serverTable.toggleRowSelection(row, true);
                  });
              } else {
                  console.error('serverTable is undefined');
              }
          })
      },2000)
      }
      else if (type==='10') {
        this.configForm.serverArray = this.defaultSelection;
      }
      else {
        this.$message({
          message: '暂不支持该类型',
          type: 'warning'
        })
      }
    },

    clickSetting() {
      this.SettingDlg = true;
    },

    cronFun() {
      this.cronVisible = true;
    },
    closeRunTimeCron(isClose) {
      this.cronVisible = isClose;
    },
    runTimeCron(cron) {
      this.configForm.rule = cron;
    },

    async getServerData() {
      const response = await this.$api.getServers(this.pro.id, 1)
      if (response.status === 200) {
        this.serverData = response.data.result;
          this.defaultSelection = this.serverData.filter(item => item.default_code === true);
          this.Selection = this.defaultSelection.map(row => row.id)

      }
    },
    handleSelectionChange(selectedRows) {
      // 选择的行可能包含多个对象
      this.configForm.serverArray = selectedRows.map(row => row.id);

    },

    dataSubmit() {
      const params = {...this.configForm}
      params.task = this.perfTask.id;
      params.update_time = this.$tools.newTime();
      params.modifier = this.username;
      params.creator = this.username;
      delete params.create_time;
      delete params.id;
      if (params.taskType === '10') delete params.rule;

      if (params.pressureMode === '10') {
        params.pressureConfig = this.FormConcurrency;
        const { ladders, ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      } else if (params.pressureMode === '20') {
        params.pressureConfig = this.FormLadder;
        const { ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      }
      params.project = this.pro.id;

      return params;
    },

    async clickSetEdit() {
      const params = this.dataSubmit()
      const response = await this.$api.setPresetting(params)
      if (response.status === 200) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }
    },

    addLadder() {
      this.FormLadder.ladders.push({
        concurrencyNumber: '',
        concurrencyStep: '',
        lastLong: ''
      });
      this.setRules()
    },

    setRules() {
      // 动态生成验证规则
      const ladderRules = {};
      // 遍历 FormLadder.ladders 数组，为每个阶梯项动态设置规则
      this.FormLadder.ladders.forEach((_, index) => {
        ladderRules[`ladders.${index}.concurrencyNumber`] = [
          { required: true, message: '并发用户数不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.concurrencyStep`] = [
          { required: true, message: '并发数步长不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.lastLong`] = [
          { required: true, message: '阶梯持续时长不能为空', trigger: 'blur' },
        ];
      });

      // 设置 rulesLadderMode 的值
      this.rulesLadderMode = ladderRules;
    },

    removeLadder(index) {
      if (this.FormLadder.ladders.length > 1) {
        this.FormLadder.ladders.splice(index, 1);
        this.setRules();
      }
    },


  },
created() {
  this.getServerData();
  this.getPresetting();
}
}
</script>

<style scoped>

/deep/ .el-scrollbar__bar {
  display: none;
}

</style>